// pages/me/me.js
var app = getApp();
var config = app.globalData.config;
var util = require('../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    active: 2,
    userInfo: {
      wxPhoto: config.appLogo,
      wxName: "微信授权"
    },
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    points: 0,
    high: '未购买'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //判断是否授权
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
      this.currentLogin();
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        this.currentLogin();
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
          this.currentLogin();
        }
      })
    }
    var userInfo = wx.getStorageSync('sUserInfo');
    if (!!userInfo) {
      app.getSUserInfo();
      this.setData({
        points: userInfo.points
      })
      var isvip = userInfo.isVip;
      var expdt = userInfo.expireDate;
      if (isvip === 1) {
        this.setData({
          high: util.formatDate(new Date(expdt), 1)
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    app.getSUserInfo();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  /**
   * 授权
   */
  onbindUserInfo(e) {
    if (e.detail.userInfo) {
      app.globalData.userInfo = e.detail.userInfo
      this.setData({
        userInfo: e.detail.userInfo,
        hasUserInfo: true
      })
      this.currentLogin();
    }
  },
  /**
   * 当前登录
   */
  currentLogin: function() {
    wx.showLoading({
      title: '授权中',
      mask: true
    })
    var that = this;
    wx.login({
      success: function(res) {
        if (res.code) {
          wx.request({
            url: config.loginUrl,
            method: "POST",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data: {
              nickName: that.data.userInfo.nickName,
              gender: that.data.userInfo.gender,
              language: that.data.userInfo.language,
              city: that.data.userInfo.city,
              province: that.data.userInfo.province,
              country: that.data.userInfo.country,
              avatarUrl: that.data.userInfo.avatarUrl,
              code: res.code
            },

            success: function(resp) {
              wx.setStorageSync("sUserInfo", resp.data.data);
              that.setData({
                points: resp.data.data.points
              })
              var isvip = resp.data.data.isVip;
              var expdt = resp.data.data.expireDate;
              if (isvip === 1) {
                that.setData({
                  high: util.formatDate(new Date(expdt), 1)
                })
              }
            },
            fail: function(e) {
              wx.showToast({
                title: '授权失败，请重试！',
                icon: 'none',
                duration: 3000
              })
            },
            complete: function() {
              wx.hideLoading();
            }
          })
        }
      },
      fail: function() {
        wx.showToast({
          title: '授权失败，请重试！',
          icon: 'none',
          duration: 3000
        })
      },
      complete: function() {
        wx.hideLoading();
      }
    });
  },
  /**
   * 获取微信地址
   */
  onAddress: function() {
    var that = this;
    wx.getSetting({
      success: function(res) {
        if (res.authSetting['scope.address']) {
          wx.chooseAddress({
            success(res) {
              wx.request({
                url: config.host + '/address',
                data: {},
                success: function() {

                }
              })
              console.log(res.userName)
              console.log(res.postalCode)
              console.log(res.provinceName)
              console.log(res.cityName)
              console.log(res.countyName)
              console.log(res.detailInfo)
              console.log(res.nationalCode)
              console.log(res.telNumber)
            }
          });
        } else {
          wx.authorize({
            scope: 'scope.address',
            success() {
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              wx.chooseAddress({
                success(res) {
                  console.log(res)
                }
              });
            }
          })
        }
      }
    })
  },
  /**
   * 打开设置
   */
  onOpenSetting: function() {
    var that = this;
    wx.openSetting({
      success: function(res) {
        if (res.authSetting["scope.userInfo"]) {
          that.currentLogin();
        } else {
          wx.removeStorageSync("sUserInfo");
        }
      }
    })
  },
  /**
   * 我参与的
   */
  onJoin: function() {
    if (this.data.hasUserInfo) {
      wx.navigateTo({
        url: '/pages/all/all?tab=0',
      })
    } else {
      wx.showToast({
        title: '请授权',
        icon: 'none'
      })
    }
  },
  /**
   * 我发布的
   */
  onMyPush: function() {
    if (this.data.hasUserInfo) {
      wx.navigateTo({
        url: '/pages/all/all?tab=1',
      })
    } else {
      wx.showToast({
        title: '请授权',
        icon: 'none'
      })
    }
  },
  /**
   * 我中奖的
   */
  onMyWin: function() {
    if (this.data.hasUserInfo) {
      wx.navigateTo({
        url: '/pages/all/all?tab=2',
      })
    } else {
      wx.showToast({
        title: '请授权',
        icon: 'none'
      })
    }
  },
  /**
   * 幸运值
   */
  onPoints: function() {
    if (this.data.hasUserInfo) {
      wx.navigateTo({
        url: '/pages/points/points',
      })
    } else {
      wx.showToast({
        title: '请授权',
        icon: 'none'
      })
    }
  },
  /**
   * 高级版
   */
  onHigh: function() {
    if (this.data.hasUserInfo) {
      wx.navigateTo({
        url: '/pages/high/high',
      })
    } else {
      wx.showToast({
        title: '请授权',
        icon: 'none'
      })
    }
  },
  /**
   * Tab切换
   */
  onClickTab(event) {
    var tab = event.currentTarget.dataset;
    var a = tab.tabindex * 1;
    if (a === 0) {
      wx.redirectTo({
        url: '/pages/index/index'
      })
    } else if (a === 1) {
      wx.navigateTo({
        url: '/pages/initiate/initiate'
      })
    }
  },
  onSingIn() {
    var userInfo = wx.getStorageSync('sUserInfo');

    wx.request({
      url: config.signInUrl,
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        UserId: userInfo.id,
        PointsRule: "REGISTRATION"
      },

      success: function(resp) {
        if (resp.data.result == 2) {
          wx.showToast({
            title: "签到成功",
            icon: 'none',
            duration: 3000
          })
        } else {
          wx.showToast({
            title: resp.data.msg,
            icon: 'none',
            duration: 3000
          })
        }
      },
      fail: function(e) {
        wx.showToast({
          title: '签到失败，请重试！',
          icon: 'none',
          duration: 3000
        })
      },
      complete: function() {}
    })
  }

})